<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Http\Resources\BookCollectionResource;
use App\Models\BookCollection;
use Illuminate\Http\Request;

/***
 * 我的书架
 * Class BookCollectionController
 * @package App\Http\Controllers\Api\V1
 */
class BookCollectionController extends ApiController
{
    /***
     * 书架列表
     * @param BookCollection $bookCollection
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(BookCollection $bookCollection, Request $request)
    {
        $query = $bookCollection->newQuery();
        if ($request->has('module_id')) {
            $query->where('module_id', $request->module_id);
        }
        if ($this->getUserId()) {
            $query->where('user_id', $this->getUserId());
        }
        $list = $query->with(['user', 'book'])->paginate();
        return $this->success('成功', BookCollectionResource::collection($list));
    }

    /***
     * 加入书架
     * @param BookCollection $bookCollection
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(BookCollection $bookCollection, Request $request)
    {
        $query = $bookCollection->newQuery();
        if ($request->has('module_id')) {
            $query->where('module_id', $request->module_id);
        }
        if ($this->getUserId()) {
            $query->where('user_id', $this->getUserId());
        }
        if ($request->has('book_id')) {
            $query->where('book_id', $request->book_id);
        }
        $data = $query->firstOrCreate([
            'module_id' => $request->module_id,
            'book_id' => $request->book_id,
            'user_id' => $this->getUserId(),
        ]);
        return $this->success('成功', BookCollectionResource::make($data)->resource);
    }
}
